package com.cskaoyan.wordmemorize.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.cskaoyan.wordmemorize.common.upload.AliOssProperties;
import com.cskaoyan.wordmemorize.service.FileUploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    private static final Logger log = LoggerFactory.getLogger(FileUploadServiceImpl.class);

//    @Value("${aliyun.oss.endpoint}")
//    private String endpoint;
//
//    @Value("${aliyun.oss.accessKeyId}")
//    private String accessKeyId;
//
//    @Value("${aliyun.oss.accessKeySecret}")
//    private String accessKeySecret;
//
//    @Value("${aliyun.oss.bucketName}")
//    private String bucketName;

    @Autowired
    AliOssProperties aliOssProperties;

    /**
     * 文件上传
     */
    @Override
    public String upload(MultipartFile file) {
        // 构造桶中的对象名称
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = UUID.randomUUID() + extension;

        String url = null;
        // 创建 OSSClient 实例
        OSS ossClient = new OSSClientBuilder().build(aliOssProperties.getEndpoint()
                ,aliOssProperties.getAccessKeyId() , aliOssProperties.getAccessKeySecret());


        try {
            // 向桶中放入指定名称的对象
            ossClient.putObject(aliOssProperties.getBucketName(), objectName, file.getInputStream());


            // 文件访问路径规则 https://BucketName.Endpoint/ObjectName
            StringBuilder stringBuilder = new StringBuilder("https://");
            stringBuilder.append(aliOssProperties.getBucketName())
                    .append(".")
                    .append(aliOssProperties.getEndpoint())
                    .append("/")
                    .append(objectName);
            url = stringBuilder.toString();
        } catch (OSSException oe) {
            log.error("阿里OSS异常，Error Message:{}", oe.getErrorMessage());
        } catch (ClientException ce) {
            log.error("阿里OSS Client异常，Error Message:{}", ce.getMessage());
        } catch (IOException e) {
            log.error("文件上传失败，Error Message:{}", e.getMessage());
        } finally {
            if (!ObjectUtils.isEmpty(ossClient)) {
                ossClient.shutdown();
            }
        }

        System.out.println(url);
        // 返回访问文件的url
        return url;
    }

    @Override
    public void deleteFile(String objectName) {
        // 创建 OSSClient 实例
        OSS ossClient = new OSSClientBuilder().build(aliOssProperties.getEndpoint()
                ,aliOssProperties.getAccessKeyId() , aliOssProperties.getAccessKeySecret());
        try {
            // 删除桶中指定对象
            ossClient.deleteObject(aliOssProperties.getBucketName(), objectName);
        } catch (OSSException oe) {
            log.error("阿里OSS异常，Error Message:{}", oe.getErrorMessage());
        } catch (ClientException ce) {
            log.error("阿里OSS Client异常，Error Message:{}", ce.getMessage());
        } finally {
            if (!ObjectUtils.isEmpty(ossClient)) {
                ossClient.shutdown();
            }
        }
    }
}